package com.zd.hamster.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class FileDownloader {

	private int cacheSize = 1024;
	
	public void down(String url, OutputStream out) throws IOException {
		
		URL u = new URL(url);
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) u.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.connect();
//			conn.getContentLength();
//			request(conn, zipname, filename);
			outputFile(conn, out);
		} finally {
			conn.disconnect();
		}
	}
	
	private void request(HttpURLConnection conn, String zipname, String filename[]) throws IOException {
		StringBuilder postData = new StringBuilder();
		postData.append("zipname=").append(URLEncoder.encode(zipname, "utf-8"));
		for (String name : filename) {
			postData.append("&").append("filename=").append(URLEncoder.encode(name, "utf-8"));
		}
		
		try(OutputStream out = conn.getOutputStream()) {
			out.write(postData.toString().getBytes());
			out.flush();
		}
	}

	private void outputFile(HttpURLConnection conn, OutputStream out) throws IOException {
		try(InputStream in = conn.getInputStream()) {
			int len = 0;
			byte[] b = new byte[cacheSize];
			while((len = in.read(b)) > -1) {
				out.write(b, 0, len);
			}
			out.flush();
		}
	}
}
